<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="活动标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入活动标题"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动地点" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入活动地点"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="活动状态" clearable style="width: 200px">
          <el-option
            v-for="dict in activity_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:activities:add']"
        >发布活动</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:activities:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:activities:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:activities:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activitiesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="activityId" width="80" />
      <el-table-column label="活动标题" align="center" prop="title" min-width="100" show-overflow-tooltip>
        <template #default="scope">
          <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="活动地点" align="center" prop="location" width="120" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参与人数" align="center" width="100">
        <template #default="scope">
          <span>{{ (scope.row.currentParticipants || 0) }}/{{ scope.row.maxParticipants || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="activity_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="报名状态" align="center" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.participated" type="success">已报名</el-tag>
          <el-tag v-else-if="(scope.row.currentParticipants || 0) >= (scope.row.maxParticipants || 0)" type="danger">已满员</el-tag>
          <el-tag v-else type="warning">可报名</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button 
            v-if="!scope.row.participated && scope.row.status === 1 && (scope.row.currentParticipants || 0) < (scope.row.maxParticipants || 0)"
            link 
            type="success" 
            icon="Plus" 
            @click="handleJoin(scope.row)"
          >报名</el-button>
          <el-button 
            v-if="scope.row.participated && scope.row.status === 1"
            link 
            type="warning" 
            icon="Minus" 
            @click="handleQuit(scope.row)"
          >取消报名</el-button>
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['system:activities:edit']"
          >修改</el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['system:activities:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="选择社团" prop="clubName">
          <el-select v-model="form.clubId" placeholder="请选择社团" style="width: 100%" @change="handleClubChange">
            <el-option
                v-for="club in userClubs"
                :key="club.clubId"
                :label="club.name"
                :value="club.clubId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动内容" prop="content">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="form.content"
            maxlength="200"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="最大参与人数" prop="maxParticipants">
          <el-input-number v-model="form.maxParticipants" :min="1" :max="1000" placeholder="请输入" style="width: 100%" />
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="dict in activity_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 活动详情对话框 -->
    <el-dialog title="活动详情" v-model="viewOpen" width="800px" append-to-body>
      <div v-if="viewForm">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="活动标题">{{ viewForm.title }}</el-descriptions-item>
          <el-descriptions-item label="活动地点">{{ viewForm.location }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ parseTime(viewForm.startTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ parseTime(viewForm.endTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
          <el-descriptions-item label="参与人数">{{ (viewForm.currentParticipants || 0) }}/{{ viewForm.maxParticipants || 0 }}</el-descriptions-item>
          <el-descriptions-item label="活动状态">
            <dict-tag :options="activity_status" :value="viewForm.status" />
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">活动内容</el-divider>
        <div class="activity-content" v-html="viewForm.content"></div>
        
        <el-divider content-position="left">报名情况</el-divider>
        <el-table :data="participantsList" style="width: 100%">
          <el-table-column prop="nickName" label="参与者" width="120">
            <template #default="scope">
              <span>{{ scope.row.nickName || scope.row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phonenumber" label="联系电话" width="120" />
          <el-table-column prop="joinTime" label="报名时间" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.joinTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                {{ scope.row.status === 1 ? '已确认' : '待确认' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Activities">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue'
import { listActivities, getActivities, delActivities, addActivities, updateActivities } from "@/api/system/activities"
import { selectUserClubs } from "@/api/system/clubs"
import { listParticipants, listParticipantsWithUser, addParticipants, delParticipants } from "@/api/system/participants"

const { proxy } = getCurrentInstance();
const { activity_status } = proxy.useDict("activity_status");
const userClubs = ref([]);
const activitiesList = ref([]);
const participantsList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const open = ref(false);
const viewOpen = ref(false);
const title = ref("");
const viewForm = ref({});

const data = reactive({
  form: {
    activityId: undefined,
    clubId: undefined,
    title: undefined,
    content: undefined,
    location: undefined,
    startTime: undefined,
    endTime: undefined,
    maxParticipants: 50,
    status: "1"
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    location: undefined,
    status: undefined
  },
  rules: {
    title: [{ required: true, message: "活动标题不能为空", trigger: "blur" }],
    content: [{ required: true, message: "活动内容不能为空", trigger: "blur" }],
    location: [{ required: true, message: "活动地点不能为空", trigger: "blur" }],
    startTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
    endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
    maxParticipants: [{ required: true, message: "最大参与人数不能为空", trigger: "blur" }],
    status: [{ required: true, message: "活动状态不能为空", trigger: "change" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询活动列表 */
function getList() {
  loading.value = true;
  listActivities(queryParams.value).then(response => {
    activitiesList.value = response.rows || [];
    total.value = response.total || 0;
    // 检查用户报名状态
    checkParticipationStatus();
    loading.value = false;
  }).catch(error => {
    console.error('获取活动列表失败:', error);
    loading.value = false;
  });
}

/** 检查用户报名状态 */
function checkParticipationStatus() {
  // 遍历活动列表，检查当前用户是否已报名每个活动
  activitiesList.value.forEach(activity => {
    // 确保数据初始化
    activity.participated = activity.participated || false;
    activity.currentParticipants = activity.currentParticipants || 0;
    activity.maxParticipants = activity.maxParticipants || 0;
  });
}

/** 社团选择变化 */
function handleClubChange(row) {
  // 可以在这里添加社团相关的逻辑
  console.info(row)
  
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    activityId: undefined,
    clubId: undefined,
    title: undefined,
    content: undefined,
    location: undefined,
    startTime: undefined,
    endTime: undefined,
    maxParticipants: 50,
    status: "1"
  };
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.activityId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  getUserClubs();
  title.value = "发布新活动";
}

/** 获取用户可发帖的社团列表 */
function getUserClubs() {
  selectUserClubs().then(response => {
    userClubs.value = response.rows || [];
  }).catch(error => {
    console.error('获取用户社团列表失败:', error);
    userClubs.value = [];
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
   getUserClubs();
  const activityId = row.activityId || ids.value[0];
  getActivities(activityId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改活动信息";
  }).catch(error => {
    console.error('获取活动详情失败:', error);
    proxy.$modal.msgError("获取活动详情失败");
  });
}

/** 查看按钮操作 */
function handleView(row) {
  getActivities(row.activityId).then(response => {
    viewForm.value = response.data || {};
    viewOpen.value = true;
    getParticipantsList(row.activityId);
  }).catch(error => {
    console.error('获取活动详情失败:', error);
    proxy.$modal.msgError("获取活动详情失败");
  });
}

/** 获取报名列表 */
function getParticipantsList(activityId) {
  listParticipantsWithUser({ activityId: activityId }).then(response => {
    participantsList.value = response.rows || [];
  }).catch(error => {
    console.error('获取报名列表失败:', error);
    participantsList.value = [];
  });
}

/** 参加活动 */
function handleJoin(row) {
  proxy.$modal.confirm('确认报名参加"' + row.title + '"活动吗？').then(() => {
    const participantData = {
      activityId: row.activityId,
      status: "1" // 待确认状态
    };
    addParticipants(participantData).then(response => {
      proxy.$modal.msgSuccess("报名成功");
      // 重新检查该活动的报名状态
      row.participated = true;
      checkActivityParticipationStatus(row.activityId);
    }).catch(error => {
      proxy.$modal.msgError("报名失败：" + (error.message || '未知错误'));
    });
  });
}

/** 取消参加活动 */
function handleQuit(row) {
  proxy.$modal.confirm('确认取消报名"' + row.title + '"活动吗？').then(() => {
    // 先查询用户的报名记录ID，然后删除
    listParticipantsWithUser({ 
      activityId: row.activityId, 
    }).then(response => {
      if (response.rows && response.rows.length > 0) {
        const participantId = response.rows[0].id;
        return delParticipants(participantId);
      } else {
        throw new Error('未找到报名记录');
      }
    }).then(() => {
      proxy.$modal.msgSuccess("取消报名成功");
      row.participated = false;
      // 重新检查该活动的报名状态
      checkActivityParticipationStatus(row.activityId);
    }).catch(error => {
      proxy.$modal.msgError("取消报名失败：" + (error.message || '未知错误'));
    });
  });
}

/** 提交表单 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      if (form.value.activityId !== undefined) {
        updateActivities(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          proxy.$modal.msgError("修改失败：" + (error.message || '未知错误'));
        });
      } else {
        addActivities(form.value).then(response => {
          proxy.$modal.msgSuccess("发布成功");
          open.value = false;
          getList();
        }).catch(error => {
          proxy.$modal.msgError("发布失败：" + (error.message || '未知错误'));
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const activityIds = row.activityId || ids.value;
  proxy.$modal.confirm('是否确认删除活动ID为"' + activityIds + '"的数据项？').then(function() {
    return delActivities(activityIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/activities/export", {
    ...queryParams.value
  }, `activities_${new Date().getTime()}.xlsx`);
}

/** 检查特定活动的报名状态 */
function checkActivityParticipationStatus(activityId) {
  // 调用后端接口检查当前用户是否已报名该活动
  listParticipantsWithUser({ 
    activityId: activityId, 
  }).then(response => {
    // 更新活动列表中的报名状态
    const activity = activitiesList.value.find(item => item.activityId === activityId);
    if (activity) {
      activity.participated = response.rows && response.rows.length > 0;
      activity.currentParticipants = response.rows ? response.rows.length : 0;
    }
  }).catch(error => {
    console.error('检查报名状态失败:', error);
  });
}

// 组件挂载时初始化数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.activity-content {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  min-height: 100px;
  line-height: 1.6;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-divider {
  margin: 20px 0;
}

/* 报名状态标签样式 */
.el-tag {
  margin-right: 5px;
}

/* 操作按钮间距 */
.el-button + .el-button {
  margin-left: 8px;
}
</style>